import React, { Component } from 'react';
import { connect } from 'dva';
import { Card, message, Button, Table, Image } from 'antd';
import { PlusOutlined } from '@ant-design/icons';
import Ellipsis from '@/components/Ellipsis';
import styles from './index.less';
import PateoSearchForm from '@/components/common/PateoSearchForm';
import PateoAuthButtons from '@/components/common/PateoAuthButtons';
import { getDictOptionsByCode, filterAuth } from '@/support/common';
import moment from 'moment';
import router from 'umi/router';
import DetailModal from './detailModal';
import SortModal from './sortModal';
import PictureModal from './pictureModal';
import AudienceDetailModal from '../../audienceManagement/audienceList/detailModal';
import MaskText from '@/components/MaskText';

const mapStateToProps = (state: any) => ({
  contentMng: state.contentMng,
  audienceList: state.audienceList,
  menu: state.menu,
  loading: state.loading.models['contentMng'],
});
const releaseStateHash = {
  1: '已发布',
  0: '未发布',
  2: '已下架',
};
class ContentList extends Component<any, any> {
  state = {
    contentId: sessionStorage.getItem('contentId'),
    tempId: sessionStorage.getItem('tempId'),
    touchWayCode: sessionStorage.getItem('touchWayCode') + '',
    isUniqImgConfig: JSON.parse(sessionStorage.getItem('isUniqImgConfig') || 'false'),
    formValues: {},
    modalVisible: false,
    contentDetailType: 'add',
    sortModalVisible: false,
    picModalVisible: false,
    contentDetailData: null,
    imgList: [],
    audienceDetailVisible: false,
    audienceDetail: null,
    dirSid: this.props.location?.query?.dirSid,
  };

  componentWillMount() {
    const { dispatch } = this.props;
    let payload = { templateSid: this.state.tempId };
    if (this.state.dirSid) {
      payload.dirSid = this.state.dirSid;
    }
    dispatch({
      type: 'contentMng/queryTempContentList',
      payload,
    });
    // TODO: 获取受众对象列表
    // dispatch({
    //   type: 'contentMng/queryAudienceList',
    //   payload: {},
    // });
    dispatch({
      type: 'audienceList/postFetchPage',
      payload: {
        url: '/audience/group/page',
        pageSize: 1000,
      },
    });
  }
  handleFlushPage = (changePagination?: any) => {
    const {
      contentMng: {
        tempContentData: { pagination },
      },
      dispatch,
    } = this.props;
    const { current, pageSize } = changePagination || pagination;
    const { formValues, dirSid } = this.state;
    let params = {
      templateSid: this.state.tempId,
      ...formValues,
      current: current,
      pageSize: pageSize,
    };
    dispatch({
      type: 'contentMng/queryTempContentList',
      payload: dirSid ? { ...params, dirSid } : { ...params },
    });
  };
  // // 分页时触发
  // tableOnChange = (pagination: any) => {
  //   const { dispatch } = this.props;
  //   const current = pagination.current;
  //   const { formValues } = this.state;
  //   const params = {
  //     templateSid: this.state.tempId,
  //     ...formValues,
  //     current: current,
  //     pageSize: pagination.pageSize,
  //   };
  //   dispatch({
  //     type: 'contentMng/queryTempContentList',
  //     payload: { ...params },
  //   });
  // };
  handleAdd = () => {
    this.setState({ modalVisible: true, contentDetailData: null, contentDetailType: 'add' });
  };
  handleEdit = (data: any) => {
    this.setState({ modalVisible: true, contentDetailData: data, contentDetailType: 'edit' });
  };
  handleView = (data: any) => {
    this.setState({ modalVisible: true, contentDetailData: data, contentDetailType: 'view' });
  };
  handleSort = (data: any) => {
    const { dispatch } = this.props;
    // 获取所有已发布的数据
    dispatch({
      type: 'contentMng/getAllPublishedContent',
      payload: { templateSid: this.state.tempId },
      callback: () => {
        this.setState({ sortModalVisible: true });
      },
    });
  };
  handleViewPic = (urlList: any, row: any) => {
    this.setState({ picModalVisible: true, imgList: urlList, contentDetailData: row });
  };
  handlePublish = (data: any, releaseState: number) => {
    const {
      menu: { userProfile },
      dispatch,
    } = this.props;
    const params = {
      sid: data.sid,
      operator: userProfile.accountName,
      releaseState,
    };
    dispatch({
      type: 'contentMng/publishTempContent',
      payload: { ...params },
      callback: (res: any) => {
        message.success(`${releaseState == 1 ? '发布成功' : '下架成功'}`);
        this.handleFlushPage();
      },
    });
  };
  handlePush = (data: any) => {};
  handleDelete = (sid: string) => {
    const { dispatch } = this.props;
    dispatch({
      type: 'contentMng/delTempContent',
      payload: { sid: sid },
      callback: (res: any) => {
        message.success('删除成功！');
        this.handleFlushPage();
      },
    });
  };
  handleBack() {
    sessionStorage.removeItem('touchWayCode');
    let pathname = this.state.dirSid
      ? `/contentMng/contentDirectory?dirSid=${this.state.dirSid}`
      : '/contentMng/contentTempList';
    router.push(pathname);
  }
  closeModal = () => {
    this.setState(
      {
        modalVisible: false,
        contentDetailData: null,
      },
      () => this.handleFlushPage(),
    );
  };
  closeSortModal = () => {
    this.setState(
      {
        sortModalVisible: false,
      },
      () => this.handleFlushPage(),
    );
  };
  closePicModal = () => {
    this.setState(
      {
        picModalVisible: false,
        contentDetailData: null,
      },
      () => this.handleFlushPage(),
    );
  };
  /**
   * 处理默认入参
   */
  handleRestParams = (fields: any) => {
    let { tempId, dirSid } = this.state;
    fields['templateSid'] = tempId;
    if (dirSid) fields['dirSid'] = dirSid;
    return fields;
  };

  /**
   * 查看受众对象详情
   * @param data
   */
  openAudienceDetailModal = (record: any) => {
    const { dispatch } = this.props;
    dispatch({
      type: 'audienceList/postObjWithRes',
      payload: {
        url: `/upload/page`,
        // 受众对象组id
        objectGroupSid: record.audienceSid,
        // 受众对象分类id
        objectClassifySid: null,
        // 页码
        page: null,
        // 每页数量
        size: null,
      },
      callback: (res: any) => {
        const { statusCode, data } = res;
        if (statusCode === '0') {
          this.setState({
            audienceDetailVisible: true,
          });
          this.detailForm.setData({
            sid: record.audienceSid,
            objectGroupName: record.audienceName,
            list: data.list,
          });
        }
      },
    });
  };
  render() {
    const {
      menu: { permissions, dicData },
      location: { pathname = '/' },
      contentMng: {
        tempContentData: { tempContentList, pagination },
        allPublishedContentList,
        // audienceList = [],
      },
      audienceList: {
        pageData: { list },
      },
      loading,
    } = this.props;
    const {
      formValues,
      modalVisible,
      contentDetailType,
      contentDetailData,
      sortModalVisible,
      picModalVisible,
      imgList,
      audienceDetailVisible,
      dirSid,
      audienceDetail,
    } = this.state;
    const imgTableData = imgList.map((item, index) => {
      return {
        src: item,
        id: index,
      };
    });
    const paginationProps = {
      showSizeChanger: true,
      showQuickJumper: true,
      ...pagination,
      showTotal: () => (
        <span>共&nbsp;{pagination === undefined ? 0 : pagination.total}&nbsp;条</span>
      ),
    };
    const searchItems = [
      {
        type: 'input',
        title: '内容名称',
        key: 'contentName',
        maxLength: 200,
      },
      {
        type: 'select',
        title: '受众对象',
        key: 'audienceSid',
        showSearch: false,
        selectOptions: list.map((item: { objectGroupName: any; sid: any }) => {
          return {
            label: item.objectGroupName,
            value: item.sid,
          };
        }),
      },
      {
        type: 'select',
        title: '发布状态',
        key: 'releaseState',
        showSearch: false,
        selectOptions: Object.keys(releaseStateHash).map(key => {
          return {
            label: releaseStateHash[key],
            value: key,
          };
        }),
      },
    ];
    const columns: Array<any> = [
      {
        title: '序号',
        dataIndex: 'index',
        width: 60,
        render: (text: any, record: any, index: any) => {
          return index + 1 + (pagination.current - 1) * pagination.pageSize;
        },
      },
      {
        title: '内容名称',
        dataIndex: 'contentName',
        render: (text: any) => (
          <Ellipsis length={16} tooltip>
            {text}
          </Ellipsis>
        ),
      },
      {
        title: '所属目录',
        dataIndex: 'dirFullName',
      },
      {
        title: '受众对象',
        dataIndex: 'audienceName',
        render: (text: any, record: any) => {
          return <a onClick={() => this.openAudienceDetailModal(record)}>{text}</a>;
        },
      },
      {
        title: '展现时机',
        dataIndex: 'displayValue',
        render: (text: any, record: any) => {
          let val = record.displayValue;
          if (record.displayType == 2) {
            // 类型为特殊日期
            // 是否精确到年
            const format = record.displayYear == 1 ? 'YYYY-MM-DD' : 'MM-DD';
            val = `${record.displayStart && moment(record.displayStart).format(format)}~~${
              record.displayEnd && moment(record.displayEnd).format(format)
            }`;
          }
          return val;
        },
      },
      {
        title: '内容版本号',
        dataIndex: 'contentVersion',
        render: (text: any) => (
          <Ellipsis length={20} tooltip>
            {text}
          </Ellipsis>
        ),
      },
      {
        title: '发布状态',
        dataIndex: 'releaseState',
        render: (text: any) => releaseStateHash[text],
      },
      {
        title: '发布时间',
        dataIndex: 'releaseTime',
        render: (text: any) => {
          return text && moment(text).format('YYYY-MM-DD HH:mm:ss');
        },
      },
      {
        title: '更新时间',
        dataIndex: 'updateTime',
        render: (text: any) => {
          return text && moment(text).format('YYYY-MM-DD HH:mm:ss');
        },
      },
      {
        title: '发布人',
        dataIndex: 'publishBy',
        render(val: any) {
          return <MaskText text={val} type="name" />;
        },
      },
      {
        title: '下架时间',
        dataIndex: 'unreleaseTime',
        render: (text: any) => {
          return text && moment(text).format('YYYY-MM-DD HH:mm:ss');
        },
      },
      {
        title: '下架人',
        dataIndex: 'unPublishBy',
        render(val: any) {
          return <MaskText text={val} type="name" />;
        },
      },
      {
        title: '操作',
        dataIndex: '操作',
        fixed: 'right',
        render: (text: any, record: any) => {
          //  内容项模版中的内容全部没有发布，则该内容项可以被编辑和删除，否则只能查看详情
          const btnsFilter =
            record.releaseState == 1 ? ['sort', 'view', 'publish'] : ['edit', 'del', 'publish'];

          // if (this.state.touchWayCode === '2' && record.releaseState != '1') {
          //   // 触达方式为推送且不为发布状态
          //   btnsFilter.push('push');
          // }
          const btnsArray = [
            {
              title: '排序',
              key: 'sort',
              auth: 'tempContent_doSort',
              onConfirm: () => this.handleSort(record),
            },
            {
              title: '详情',
              key: 'view',
              auth: 'tempContent_doView',
              onConfirm: () => this.handleView(record),
            },
            {
              title: '编辑',
              key: 'edit',
              auth: 'tempContent_doEdit',
              onConfirm: () => this.handleEdit(record),
            },
            {
              title: '删除',
              key: 'del',
              auth: 'tempContent_doDel',
              message: '是否确认删除？',
              Popconfirm: true,
              onConfirm: () => this.handleDelete(record.sid),
            },
            {
              title: record.releaseState == 1 ? '取消发布' : '发布',
              key: 'publish',
              auth: 'tempContent_doPublish',
              message: `是否确认${record.releaseState == 1 ? '取消发布' : '发布'}？`,
              Popconfirm: true,
              onConfirm: () => this.handlePublish(record, record.releaseState == 1 ? 2 : 1),
            },
            // {
            //   title: '推送配置',
            //   key: 'push',
            //   auth: 'tempContent_doPush',
            //   onConfirm: () => this.handlePush(record),
            // },
          ];
          const btns = btnsArray.filter(item => {
            return btnsFilter.indexOf(item.key) > -1;
          });
          return <PateoAuthButtons pathname={pathname} btns={btns} max={3} />;
        },
      },
    ];

    if (this.state.isUniqImgConfig) {
      const imgCol = {
        title: '缩略图',
        dataIndex: 'imageUrl',
        width: 100,
        render: (text: any, record: any) => {
          const contentList = (record.contentJson && JSON.parse(record.contentJson)) || [];
          // const imgList = text?.split(',') || [];
          const imgList =
            contentList.find((item: { type: string }) => item.type == '3')?.content || [];
          if (imgList.length) {
            return imgList.length === 1 ? (
              <Image
                src={imgList[0].url}
                style={{ width: 75, height: 30, marginLeft: 5, marginTop: 5 }}
                fallback=""
              />
            ) : (
              <img
                src={imgList[0].url}
                style={{ width: 75, height: 30, marginLeft: 5, marginTop: 5, cursor: 'pointer' }}
                onClick={() => {
                  this.handleViewPic(imgList, record);
                }}
              />
            );
          }
        },
      };
      columns.splice(1, 0, imgCol);
    }
    return (
      <div>
        <Card title="" bordered={false}>
          <PateoSearchForm
            searchItems={searchItems}
            fetchParams={{
              type: 'contentMng/queryTempContentList',
            }}
            saveFormValues={(val: any) =>
              this.setState({ formValues: Object.assign(formValues, val), selectedRowKeys: [] })
            }
            handleFormReset={() => this.setState({ formValues: {} })}
            handleFieldsValue={this.handleRestParams}
          />
        </Card>
        <Card bordered={false} style={{ marginTop: 12 }}>
          <div className="my_newItem">
            {filterAuth('tempContent_doAdd', permissions, pathname) && (
              <Button
                onClick={() => this.handleAdd()}
                size="small"
                icon={<PlusOutlined />}
                type="primary"
              >
                新增
              </Button>
            )}
          </div>
          <Table
            className={styles['customer-grid']}
            loading={loading}
            rowKey={(row: { sid: any }) => row.sid}
            columns={columns}
            size="small"
            pagination={paginationProps}
            onChange={this.handleFlushPage}
            dataSource={tempContentList}
            scroll={{ x: 'max-content' }}
          />
        </Card>
        <Card bordered={false}>
          <Button onClick={() => this.handleBack()} size="small" type="primary">
            返回
          </Button>
        </Card>
        {modalVisible && (
          <DetailModal
            modalVisible={modalVisible}
            contentDetails={contentDetailData}
            type={contentDetailType}
            closeModal={this.closeModal}
            dirSid={dirSid}
            dicData={dicData}
          />
        )}
        {sortModalVisible && (
          <SortModal
            modalVisible={sortModalVisible}
            contentList={allPublishedContentList}
            closeModal={this.closeSortModal}
          />
        )}
        {picModalVisible && (
          <PictureModal
            modalVisible={picModalVisible}
            contentDetails={contentDetailData}
            imgList={imgTableData}
            closeModal={this.closePicModal}
          />
        )}
        {audienceDetailVisible && (
          <AudienceDetailModal
            onRef={(val: any) => (this.detailForm = val)}
            modalVisible={audienceDetailVisible}
            closeModal={() => {
              this.setState({
                audienceDetailVisible: false,
              });
            }}
          />
        )}
      </div>
    );
  }
}
export default connect(mapStateToProps)(ContentList);
